﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WCS_Quartz_Task
{
    /// <summary>
    /// 定时任务管理类
    /// </summary>
    public class QuartzJobProcess : IQuartzJobProcess
    {
        private IScheduler quartzJob;

        public QuartzJobProcess()
        {
            CreatJobAsync();
        }

        public async Task CreatJobAsync()
        {
            if (quartzJob is null)
            {
                var schedulerFactory = new StdSchedulerFactory();
                quartzJob = await schedulerFactory.GetScheduler();
                await quartzJob.Start();
            }
        }

        /// <summary>
        /// 添加定时任务
        /// </summary>
        /// <param name="jobDetail"></param>
        /// <param name="trigger"></param>
        /// <returns></returns>
        public async Task AddJobAsync(IJobDetail jobDetail, ITrigger trigger)
        {
            if (quartzJob.IsShutdown)
            {
                return;
            }
            await quartzJob.ScheduleJob(jobDetail, trigger);
        }
        /// <summary>
        /// 移除指定的Job
        /// </summary>
        /// <param name="jobKey"></param>
        /// <returns></returns>
        public async Task DeleteJobAsync(string jobName,string group)
        {
            if (quartzJob.IsShutdown)
            {
                return;
            }
            JobKey jk = new JobKey(jobName, group);
            await quartzJob.DeleteJob(jk);
        }
        /// <summary>
        /// 暂停指定任务
        /// </summary>
        /// <returns></returns>
        public async Task PauseJobAsync(string jobName, string group)
        {
            if (quartzJob.IsShutdown)
            {
                return;
            }
            JobKey jk = new JobKey(jobName, group);
            await quartzJob.PauseJob(jk);
        }

        public async Task QuartzShutdownAsync()
        {
            if (quartzJob.IsShutdown)
            {
                return;
            }
            await quartzJob.Shutdown();
        }

        public bool QueryQuartzState()
        {
            return quartzJob.IsShutdown;
        }
    }
}
